package com.example.aijiancece.database;

import android.content.Context;

import com.example.aijiancece.database.entity.UserEntity;

import java.util.UUID;

public class UserRepository {
    private final AppDatabase database;
    private static UserRepository instance;

    private UserRepository(Context context) {
        database = AppDatabase.getInstance(context);
    }

    public static synchronized UserRepository getInstance(Context context) {
        if (instance == null) {
            instance = new UserRepository(context.getApplicationContext());
        }
        return instance;
    }

    public void register(String username, String password, OnResultListener listener) {
        new Thread(() -> {
            try {
                UserEntity existingUser = database.userDao().findByUsername(username);
                if (existingUser != null) {
                    listener.onError("用户名已存在");
                    return;
                }

                String id = UUID.randomUUID().toString();
                UserEntity user = new UserEntity(id, username, password);
                database.userDao().insert(user);
                listener.onSuccess();
            } catch (Exception e) {
                listener.onError(e.getMessage());
            }
        }).start();
    }

    public void login(String username, String password, OnResultListener listener) {
        new Thread(() -> {
            try {
                UserEntity user = database.userDao().login(username, password);
                if (user != null) {
                    listener.onSuccess();
                } else {
                    listener.onError("用户名或密码错误");
                }
            } catch (Exception e) {
                listener.onError(e.getMessage());
            }
        }).start();
    }

    public void changePassword(String username, String oldPassword, String newPassword, OnResultListener listener) {
        new Thread(() -> {
            try {
                int updatedRows = database.userDao().updatePassword(username, oldPassword, newPassword);
                if (updatedRows > 0) {
                    listener.onSuccess();
                } else {
                    listener.onError("原密码错误");
                }
            } catch (Exception e) {
                listener.onError(e.getMessage());
            }
        }).start();
    }

    public interface OnResultListener {
        void onSuccess();
        void onError(String error);
    }
} 